function makeUser() {
return {
name: "John",
ref() {
return this;
}
};
}
let user = makeUser();
alert(user.ref().name);
From what I've learned from thistutorial, they define as the object before dot and since this is the return value of the function, I thought it would be user.
And this tutorial is defining it as the object that is executing the current function.
I think the object that is executing the current function is user. When you replace this by its value it becomes alert(user.user.name);.
The value of "this" doesn't refer to the name of an object, it refers to the object itself. So there is no "duplication" here, you're just returning an object, which happens to be the same object you started with.
This is perhaps clearer if you separate things out:
function makeUser() {
// Create an object
let myObject = {
name: "John"
};
// Create a function which returns that object
let myFunction = function(){ return myObject; };
// Store the function on the object
myObject.ref = myFunction;
// Return the new object
return myObject;
}
// Create an object
let user = makeUser();
// Get the name from the object
alert(user.name);
// Call the ref() function, which happens to return the same object
let otherUser = user.ref();
// Get the name again
alert(otherUser.name);
// No matter how many times you call .ref() it will return the same object
alert(user.ref().ref().ref().ref().name);
this refers to a object the function function belongs to or window object if it belongs to no objects. in this case ref() function is returning the owner object for e.g.,
when you call ref() it will return like this
{ name: 'John', ref: [Function: ref] }